package com.common.android.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.text.TextUtils;
import android.util.Log;
import android.util.Patterns;
import android.webkit.URLUtil;

/**
 * URL相关工具类
 * <br>Created 2014-8-27 下午2:39:24
 * @version  
 * @author   huangyx		
 * @see 	 
 * Copyright(c) 2009-2014, TQ Digital Entertainment, All Rights Reserved
 */
public class UrlUtils {
    
    private static final String TAG = "UrlUtils";
    //修改Patterns.GOOD_IRI_CHAR，过滤双字节
    private static final String GOOD_IRI_CHAR ="a-zA-Z0-9";
//    private static final String HTTP_HEADER = "http://";
    private static final String UID_TAG = "?uid=";
    private static final String KEY_TAG = "&k=";
    //修改系统的URL正则，过滤双字节，去除url后面必须带结束字节
    public static final Pattern WEB_URL = Pattern.compile(
            "((?:(http|https|rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)"
            + "\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_"
            + "\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)"
            + "((?:(?:[" + GOOD_IRI_CHAR + "][" + GOOD_IRI_CHAR + "\\-]{0,64}\\.)+"   // named host
            + Patterns.TOP_LEVEL_DOMAIN_STR_FOR_WEB_URL
            + "|(?:(?:25[0-5]|2[0-4]" // or ip address
            + "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]"
            + "|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1]"
            + "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}"
            + "|[1-9][0-9]|[0-9])))"
            + "(?:\\:\\d{1,5})?)" // plus option port number
            + "(\\/(?:(?:[" + GOOD_IRI_CHAR + "\\;\\/\\?\\:\\@\\&\\=\\#\\~"  // plus option query params
            + "\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?",
            Pattern.CASE_INSENSITIVE // 忽略大小写
	        );
    
    /**
     * 判断某个字符串是不是个URL
     * <br>Created 2014-3-13下午3:42:12 
     * @param str 输入字符串
     * @return true 字符串是URL；
     *         false 字符串不是URL或者为null
     * @author       cb
     */
    public static boolean isUrl(String str){
        if (TextUtils.isEmpty(str)){
            return false;
        }
        Matcher matcher = WEB_URL.matcher(str);
        return matcher.find();
    }
    
    /**
     * 根据URL获取KEY
     * <br>Created 2013-8-5下午3:39:36 
     * @param url 源URL字符串
     * @return URL的KEY 
     * @author cb
     */
    public static String getKey(String url){
        String[] keys=url.split("&");
        try {
            String key=keys[1].replace("k=", "");
            return key;
        } catch (Exception e) {
            return "";
        }
    }
    
    /**
     * 从URL中获取uid
     * <br>Created 2014-8-22 下午8:10:00
     * @param data 源URL
     * @return uid
     * @author       huangyx
     */
    public static long getUidFromUrl(String data){
        int start = data.indexOf(UID_TAG);
        int end = data.indexOf(KEY_TAG);
        if (start < 0 || end < 0) {
            return 0;
        }
        
        try {
            String uid = data.substring(start+UID_TAG.length(), end);
            long lUid = Long.parseLong(uid);
            return lUid;
        } catch(StringIndexOutOfBoundsException e){
            Log.e(TAG, "get uid index out of bounds");
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
    /**
     * 判断url是否为http或ftp协议URL,对于非ftp或http协议的URL，添加http协议头
     * <br>Created 2013-11-25下午5:05:06
     * @param url 原始url
     * @return 添加协议头的url
     * @author zxq
     */
    public static String completeUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return "";
        }
        if (!url.startsWith("ftp") && !url.startsWith("Ftp") && !URLUtil.isNetworkUrl(url)) {
            return "http://" + url;
        }
        return url;
    }
    
    /**
     * 对没有http，https头的url添加头部
     * <br>Created 2013-12-20下午5:31:35
     * @param url 原始url
     * @return 添加协议头的url
     * @author huangszh
     */
    public static final String makeUrl(String url) {
        String[] prefixes = new String[] { "http://", "https://", "rtsp://"};
        if(!url.startsWith("ftp") && !url.startsWith("Ftp") ){
            boolean hasPrefix = false;
                
            for (int i = 0; i < prefixes.length; i++) {
                if (url.regionMatches(true, 0, prefixes[i], 0,
                                      prefixes[i].length())) {
                    hasPrefix = true;

                    // Fix capitalization if necessary
                    if (!url.regionMatches(false, 0, prefixes[i], 0,
                                           prefixes[i].length())) {
                        url = prefixes[i] + url.substring(prefixes[i].length());
                    }

                    break;
                }
            }

            if (!hasPrefix) {
                url = prefixes[0] + url;
            }
        }
        return url;
    }
    
    /**
     * 获取文件的Uri
     * <br>Created 2014-8-25 下午9:00:49
     * @param path 文件路径
     * @return 文件的Uri
     * @author       huangyx
     */
    public static String getFileUri(String path){
        return "file://" + path;
    }
    
    /**
     * @n<b>函数名称</b>     :isHtml
     * @brief 判断某个字符串是不是个URL
     * @version    Ver 1.3.3_modularization
     * @param  @param str
     * @param  @return
     * @return boolean
     * @<b>作者</b>          :  cb
     * @<b>创建时间</b>      :  2014-3-13下午3:42:12      
    */
    public static boolean isHtml(String str){
        if (TextUtils.isEmpty(str)){
            return false;
        }
        Matcher matcher = WEB_URL.matcher(str);
        return matcher.find();
    }
}
